<template>
  <div class="container">
    <div class="app-container">
      <!-- 1.按钮 -->
      <div class="role-operate">
        <el-button type="primary" size="mini" @click="showDialog = true">添加角色</el-button>
      </div>
      <!-- 2.列表组件 -->
      <el-table :data="list">
        <el-table-column prop="name" align="center" label="角色" width="200">
          <template v-slot="{ row }">
            <el-input v-if="row.isEdit" v-model="row.editRow.name" size="mini" type="text" />
            <span v-else>{{ row.name }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="state" align="center" label="启用" width="200">
          <template v-slot="{ row }">
            <el-switch v-if="row.isEdit" v-model="row.editRow.state" :active-value="1" :inactive-value="0" />
            <span v-else> {{ row.state === 1 ? "已启用" : row.state === 0 ? "未启用" : "无" }} </span>
          </template>
        </el-table-column>
        <el-table-column prop="description" align="center" label="描述">
          <template v-slot="{ row }">
            <el-input v-if="row.isEdit" v-model="row.editRow.description" size="mini" type="textarea" />
            <span v-else>{{ row.description }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作">
          <template v-slot="{ row }">
            <template v-if="row.isEdit">
              <el-button size="mini" type="primary" @click="btnEditOk(row)">确定</el-button>
              <el-button size="mini" @click="row.isEdit = false">取消</el-button>
            </template>
            <template v-else>
              <el-button size="mini" type="text" @click="btnPermission(row.id)">分配权限</el-button>
              <el-button size="mini" type="text" @click="btnEditRow(row)">编辑</el-button>
              <el-popconfirm title="这是一段内容确定删除吗？" @onConfirm="btnCancelRow(row.id)">
                <el-button slot="reference" style="margin-left:15px" size="mini" type="text">删除</el-button>
              </el-popconfirm>
            </template>
          </template>
        </el-table-column>
      </el-table>
      <!-- 3.分页组件 -->
      <el-row type="flex" style="height: 60px" align="middle" justify="end">
        <el-pagination
          layout="prev, pager, next"
          :current-page="pageParams.page"
          :page-size="pageParams.pagesize"
          :total="pageParams.total"
          @current-change="currentChange"
        />
      </el-row>
    </div>
    <!-- 添加角色弹层 -->
    <el-dialog width="500px" title="新增角色" :visible.sync="showDialog" @close="btnCancel">
      <el-form ref="roleForm" :model="roleForm" :rules="rules" label-width="120px">
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="roleForm.name" style="width:300px" size="mini" />
        </el-form-item>
        <el-form-item label="启用" prop="state">
          <el-switch v-model="roleForm.state" :active-value="1" :inactive-value="0" size="mini" />
        </el-form-item>
        <el-form-item label="角色描述" prop="description">
          <el-input v-model="roleForm.description" type="textarea" :rows="3" style="width:300px" />
        </el-form-item>
      </el-form>
      <el-row type="flex" justify="center" align="middle">
        <el-button size="small" type="primary" @click="btnOk">确定</el-button>
        <el-button size="small" @click="btnCancel">取消</el-button>
      </el-row>
    </el-dialog>

    <!-- 权限分配弹层 -->
    <el-dialog :visible.sync="showPermissionDialog" title="分配权限">
      <el-tree
        ref="permTree"
        node-key="id"
        :data="permissionData"
        :props="{ label: 'name' }"
        show-checkbox
        default-expand-all
        :default-checked-keys="permIds"
      />
      <!-- 默认选中需要 default-checked-keys属性绑定数组，node-key="id"指定绑定的id-->
      <el-row slot="footer" type="flex" justify="center">
        <el-col :span="6">
          <el-button type="primary" size="mini" @click="btnPermissionOK">确定</el-button>
          <el-button size="mini" @click="showPermissionDialog = false">取消</el-button>
        </el-col>
      </el-row>
    </el-dialog>
  </div>
</template>
<script>
import { getRoleList, addRole, editRow, delRow, getRoleDetail, assignPerm } from '@/api/role'
import { getPermissionList } from '@/api/permission'
import { transListToTreeData } from '@/utils'
export default {
  name: 'Role',
  data() {
    return {
      list: [],
      pageParams: {
        page: 1,
        pagesize: 10,
        total: 0
      },
      showDialog: false,
      roleForm: {
        name: '',
        state: '',
        description: ''
      },
      rules: {
        name: [{ required: true, message: '角色名称不能为空', trigger: 'blur' }],
        state: [{ required: true, message: '启用状态不能为空', trigger: 'blur' }],
        description: [{ required: true, message: '角色描述不能为空', trigger: 'blur' }]
      },
      showPermissionDialog: false,
      permissionData: [], // 所有权限列表
      currentRoleId: null, // 当前角色的id
      permIds: [] // 当前角色所拥有的权限id们
    }
  },
  created() {
    this.getRoleList()
  },
  methods: {
    async getRoleList() {
      const { rows, total } = await getRoleList(this.pageParams)
      this.list = rows
      this.pageParams.total = total
      // 标记行是否是编辑状态
      this.list.forEach((item) => {
        // 此处数据不是响应式的，因为是后来添加的
        // this.$set(目标对象，属性名称，初始值) 对目标对象，添加属性和值
        this.$set(item, 'isEdit', false)
        this.$set(item, 'editRow', {
          name: item.name,
          state: item.state,
          description: item.description
        })
      })
    },
    currentChange(newPage) {
      this.pageParams.page = newPage
      this.getRoleList()
    },
    btnOk() {
      this.$refs.roleForm.validate(async isOk => {
        if (isOk) {
          await addRole(this.roleForm)
          this.$message.success('新增角色成功')
          this.getRoleList()
          this.btnCancel()
        }
      })
    },
    btnCancel() {
      this.$refs.roleForm.resetFields()
      this.showDialog = false
    },
    // 进入编辑
    btnEditRow(row) {
      console.log(row)
      row.isEdit = true
      // 每次点进编辑状态，应用当前行的row数据，而不是上一次editrow的数据，因为这里还没有发送修改接口
      row.editRow.name = row.name
      row.editRow.state = row.state
      row.editRow.description = row.description
    },
    // 编辑确认
    async btnEditOk(row) {
      console.log(row)
      // 校验内容非空
      if (row.editRow.name && row.editRow.description) {
        await editRow({ ...row.editRow, id: row.id })
        this.$message.success('修改成功')
        // 把最新数据赋值给row,并退出编辑模式  await里面不能对row进行操作的代码报错，为了避免报错，用以下方法
        // Object.assign(目标对象，源对象)用于合并对象
        Object.assign(row, { ...row.editRow, isEdit: false })
        this.getRoleList()
      } else {
        this.$message.warning('角色和描述不能为空')
      }
    },
    // 删除
    async btnCancelRow(id) {
      await delRow(id)
      this.$message.success('删除成功')
      if (this.list.length === 1 && this.pageParams.page > 1) {
        this.pageParams.page--
      }
      this.getRoleList()
    },
    // 分配权限弹框
    async btnPermission(id) {
      // 2.获取当前点击的角色的权限
      this.currentRoleId = id
      // 1.获取当前角色的所有权限,转为树形结构
      const { permIds } = await getRoleDetail(id)
      this.permIds = permIds
      this.permissionData = transListToTreeData(await getPermissionList(), 0)
      this.showPermissionDialog = true
    },
    async btnPermissionOK() {
      await assignPerm({
        id: this.currentRoleId,
        // 使用 this.$refs.permTree 来访问 el-tree 组件，并调用 getCheckedKeys 方法来获取被选中节点的 key。
        permIds: this.$refs.permTree.getCheckedKeys()
      })
      this.$message.success('分配角色成功')
      this.showPermissionDialog = false
    }
  }
}
</script>
<style scoped>
.role-operate {
  padding: 10px;
}
</style>
